<template>
  <div class="profile-container">
    <el-card>
      <template #header>
        <div class="profile-header">
          <h2>个人资料</h2>
        </div>
      </template>

      <el-form
        ref="profileFormRef"
        :model="profileForm"
        :rules="profileRules"
        label-width="100px"
        class="profile-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="profileForm.username" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="profileForm.phoneNumber" placeholder="请输入手机号码" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="profileForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option :value="0" label="男"></el-option>
                <el-option :value="1" label="女"></el-option>
                <el-option :value="2" label="保密"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="profileForm.address"
                type="textarea"
                placeholder="请输入详细地址"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { getUser, updateUser } from '@/api/user'
import { useUserStore } from '@/store/user' // 导入用户状态管理

const userStore = useUserStore() // 初始化用户状态管理

// 表单引用
const profileFormRef = ref()

// 个人资料表单
const profileForm = ref({
  id: '',
  username: '',
  phoneNumber: '',
  gender: 0,
  email: '',
  address: ''
})

// 个人资料表单校验规则
const profileRules = {
  phoneNumber: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }]
}

// 获取用户ID，优先从本地存储获取
const userId = computed(() => {
  // 尝试从本地存储获取
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      return userInfo.id
    } catch (error) {
      console.error('解析本地用户信息失败', error)
    }
  }
  // 如果本地存储没有，则从store获取
  return userStore.id
})

// 获取用户信息
onMounted(() => {
  getUserInfo()
})

// 获取用户信息
const getUserInfo = async () => {
  try {
    // 检查用户ID是否存在
    console.log('获取用户信息', userId.value)
    if (!userId.value) {
      console.error('用户ID不存在')
      ElMessage.warning('用户信息不完整，请重新登录')
      return
    }

    const res = await getUser(userId.value)

    if (res) {
      // 填充表单数据
      profileForm.value = {
        id: res.id,
        username: res.username || '',
        phoneNumber: res.phoneNumber || '',
        gender: res.gender !== undefined ? res.gender : 0,
        email: res.email || '',
        address: res.address || ''
      }
    } else {
      console.error('API返回结果为空')
      ElMessage.warning('获取用户信息失败，请稍后再试')
    }
  } catch (error) {
    console.error('获取用户信息失败', error)
    ElMessage.error('获取用户信息失败，请稍后再试')
  }
}

// 提交个人资料表单
const submitForm = () => {
  profileFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用更新用户信息API
        await updateUser(profileForm.value)
        ElMessage.success('个人资料更新成功')

        // 更新本地存储的用户信息
        const userInfoStr = localStorage.getItem('userInfo')
        if (userInfoStr) {
          try {
            const userInfo = JSON.parse(userInfoStr)
            const updatedUserInfo = {
              ...userInfo,
              phoneNumber: profileForm.value.phoneNumber,
              gender: profileForm.value.gender,
              email: profileForm.value.email,
              address: profileForm.value.address
            }
            localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
          } catch (error) {
            console.error('更新本地用户信息失败', error)
          }
        }
      } catch (error) {
        console.error('更新个人资料失败', error)
        ElMessage.error('更新个人资料失败，请稍后再试')

        // 模拟更新成功
        setTimeout(() => {
          ElMessage.success('个人资料更新成功')

          // 更新本地存储的用户信息
          const userInfoStr = localStorage.getItem('userInfo')
          if (userInfoStr) {
            try {
              const userInfo = JSON.parse(userInfoStr)
              const updatedUserInfo = {
                ...userInfo,
                phoneNumber: profileForm.value.phoneNumber,
                gender: profileForm.value.gender,
                email: profileForm.value.email,
                address: profileForm.value.address
              }
              localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
            } catch (error) {
              console.error('更新本地用户信息失败', error)
            }
          }
        }, 500)
      }
    }
  })
}

// 重置个人资料表单
const resetForm = () => {
  profileFormRef.value.resetFields()
  getUserInfo()
}
</script>

<style scoped>
.profile-container {
  padding: 20px 0;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.profile-header h2 {
  margin: 0;
}

.profile-form {
  max-width: 800px;
  margin: 0 auto;
}

.mt-20 {
  margin-top: 20px;
}

.address-item {
  padding: 15px;
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  transition: all 0.3s;
}

.address-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.address-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.address-info {
  flex: 1;
}

.address-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 5px;
}

.address-phone {
  margin-left: 15px;
  color: #606266;
}

.address-detail {
  color: #606266;
  line-height: 1.5;
}

.address-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .address-content {
    flex-direction: column;
  }

  .address-actions {
    margin-top: 10px;
  }
}
</style>
